<?php
namespace app\api\controller;
use app\common\controller\CommonApi;
use Pay\Pay;
use think\Db;
/**
 * 服务模块
 */
class Service extends CommonApi{
    protected $tn = 'common/service';


    /**
     * [issue 发布服务]
     * @return [type] [description]
     */
    public function issue(){
        if(isset($this->post['image']) && trim($this->post['image'])){
            $image_count = count(explode(',',trim($this->post['image'])));
            if($image_count > 9){
                $this->apiReturn(0,'最多可长传9张图片');
            }
        }

        if(intval($this->post['type']) == 1){
            if(!isset($this->post['pay_price']) || floatval($this->post['pay_price']) <= 0){
                $this->apiReturn(0,'请输入定金金额');
            }

            if(!isset($this->post['price']) || floatval($this->post['price']) <= 0){
                $this->apiReturn(0,'请输入价格');
            }

            $min_issue_price = db('web_config')->where('key','need_min_price')->value('value');
            if(floatval($this->post['pay_price']) < floatval($min_issue_price)){
                $this->apiReturn(0,'最低金额不得小于'.$min_issue_price);
            }
        }

        $model = model($this->tn);
        $this->post['user_id'] = UID;
        $result = $model->validate($this->tn)->allowField(true)->save($this->post);
        if($result === false){
            $this->apiReturn(0, $model->getError());
        }
        $this->apiReturn(1,'发布成功');
    }

    //删除服务
    public function delService(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        
        $info = model($this->tn)->where('user_id',UID)->where('id',intval($this->post['id']))->where('status',1)->find();

        if(is_null($info)){
            $this->apiReturn(0,'该服务不存在或已被删除');
        }
        if(!$info->save(['status' => 0])){
            $this->apiReturn(0,'删除失败，请稍后再试');
        }
        $this->apiReturn(1,'删除成功');
    }

    //订单详情
    public function orderInfo(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'订单id丢失');
        }
        $info = db('service_buy')->alias('b')
            ->join(['bz_service' => 's'],'s.id =  b.foreign_key','left')
            ->join(['bz_user' => 'u'],'u.id = s.user_id','left')
            ->where('b.id',intval($this->post['id']))
            ->field('b.id,FROM_UNIXTIME(b.add_time,"%Y-%m-%d %H:%i") as create_time,order_no,FROM_UNIXTIME(b.pay_time,"%Y-%m-%d %H:%i") as pay_time,FROM_UNIXTIME(b.finish_time,"%Y-%m-%d %H:%i") as finish_time,b.price,b.sum_price,title,image,u.nick_name,u.photo_path,b.status')
            ->find();
        $info['user_nick'] = $this->user_info['nick_name'];
        $info['user_photo'] = $this->user_info['photo_path'];
        $info['image'] = empty($info['image']) ? "" : explode(',',$info['image'])[0];
        $this->apiReturn(1,'订单详情',$info);
    }

    //购买服务-提交订单
    public function addOrder(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $info = db('service')->where('id',intval($this->post['id']))->where('status',1)->find();
        if(is_null($info)){
            $this->apiReturn(0,'该服务不存在或已被删除');
        }
        if($info['user_id'] == UID){
            $this->apiReturn(0,'不能购买自己的服务');
        }

        //无偿服务无需支付
        if($info['type'] == 1){
            $data['price'] = $info['pay_price'];
            $data['sum_price'] = $info['price'];
        }else{
            $data['status'] = 1;
            $data['order_no'] = date('YmdHis').rand(10000,99999);
        }
        $data['issue_id'] = $info['user_id'];
        $data['service_type'] = $info['type'];
        $data['buy_user'] = UID;
        $data['foreign_key'] = $info['id'];
        if(!model('common/service_buy')->save($data)){
            $this->apiReturn(0,'下单失败，请稍后再试');
        }

        $this->apiReturn(1,'下单成功',model('common/service_buy')->id);
    }

    //订单支付
    public function pay(){
        $validate = new \think\validate([
            'id' => 'require',
            'pay_type' => 'require|in:0,1,2'
        ],[
            'id.require' => '参数id丢失',
            'pay_type.require' => '请选择支付方式',
            'pay_type.in' => '支付方式错误'
        ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }
        $info = model('common/service_buy')->where('buy_user',UID)->where('id',intval($this->post['id']))->find();
        if(is_null($info)){
            $this->apiReturn(0,'订单不存在或已被删除');
        }
        if($info['status'] != 0){
            $this->apiReturn(0,'订单状态有误');
        }
        if($info['service_type'] == 2){
            $this->apiReturn(0,'无偿服务无需支付');
        }
        $service_info = db('service')->where('id',$info['foreign_key'])->where('status',1)->find();
        if(is_null($service_info)){
            $this->apiReturn(0,'该服务不存在或已被删除');
        }

        $order_no = date('YmdHis').rand(10000,99999);

        //余额支付
        if($this->post['pay_type'] == 0){
            if($this->user_info['balance'] < $info['price']){
                $this->apiReturn(0,'余额不足');
            }
            db()->startTrans();
            if(!$info->save([
                'order_no' => $order_no,
                'pay_time' => time(),
                'status' => 1
            ])){
                db()->rollback();
                $this->apiReturn(0,'状态修改失败');
            }

            //售卖者信息
            $service_user = model('common/user')->getUserInfo(['id' => $service_info['user_id']],'grade,grade_end_time,from_city');

            //佣金
            if($service_user['grade'] == 1){
                $yongjin = db('web_config')->where('key','h_yongjin')->value('value');
            }else{
                $yongjin = db('web_config')->where('key','p_yongjin')->value('value');
            }

            $seller_price = sprintf('%.2f',$info['price'] - $yongjin);  //售卖者所得金额

            //修改账户余额
            if(!db('user')->where('id',UID)->setDec('balance',$info['price'])){
                db()->rollback();
                $this->apiReturn(0,'余额扣除失败');
            }

            if(!db('user')->where('id',$service_info['user_id'])->update([
                'balance' => ['inc',$seller_price],
                'service_count' => ['inc',1]
            ])){
                db()->rollback();
                $this->apiReturn(0,'信息修改失败');
            }

            //添加交易明细
            $insert_count = db('bill')->insertAll([
                [
                    'user_id' => UID,
                    'type' => 6,
                    'num' => $info['price'],
                    'foreign_key' => $info['id'],
                    'add_time' => time()
                ],[
                    'user_id' => $service_info['user_id'],
                    'type' => 8,
                    'num' => $seller_price,
                    'foreign_key' => $info['id'],
                    'add_time' => time()
                ]
            ]);

            if(!$insert_count){
                db()->rollback();
                $this->apiReturn(0,'交易明细添加失败');
            }

            //通知
            $infor_count = db('information')->insertAll([
                [
                    'user_id' => UID,
                    'type' => 6,
                    'content' => '服务-'.$service_info['title'].'购买成功',
                    'add_time' => time()
                ],[
                    'user_id' => $service_info['user_id'],
                    'type' => 8,
                    'content' => '服务-'.$service_info['title'].'被购买',
                    'add_time' => time()
                ]
            ]);
            
            if(!$infor_count){
                db()->rollback();
                $this->apiReturn(0,'信息添加失败');
            }
            

            if(!model('common/admin_bill')->addBill($service_user['from_city'],$yongjin,$info['id'],3)){
                db()->rollback();
                $this->apiReturn(0,'操作失败，未知错误');
            }

            
            db()->commit();

            //推送
            if($service_info['hint']){
                JPush($service_info['user_id'],'服务-'.$service_info['title'].'被人接单');
            }
            $this->apiReturn(1,'购买成功');
        }

        //微信支付
        if($this->post['pay_type'] == 1){
            $options = [
                'out_trade_no' => $order_no,
                'total_fee' => $info['price'] * 100,
                'body' => '购买服务',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                'attach' => serialize(['attach' => 4,'id' => intval($this->post['id'])])
            ];

            $pay = new Pay(config('pay'));

            try{
                $result = $pay->driver('wechat')->gateway('app')->apply($options);
                $this->apiReturn(1,'微信支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
        //支付宝支付
        if($this->post['pay_type'] == 2){
            $options = [
                'out_trade_no' => $order_no,
                'total_amount' =>  $info['price'],
                'subject' => '购买服务',
                'passback_params' => UrlEncode(serialize(['passback_params' => 4,'id' => intval($this->post['id'])]))
            ];
            $pay = new Pay(config('pay'));
            try{
                $result = $pay->driver('alipay')->gateway('app')->apply($options);
                $this->apiReturn(1,'支付宝支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
    }

    //确认完成
    public function comFinish(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }

        $model = model('common/service_buy')->where('buy_user',UID)->where('id',intval($this->post['id']))->find();
        if(is_null($model)){
            $this->apiReturn(0,'订单不存在或已被删除');
        }

        if($model['status'] != 1){
            $this->apiReturn(0,'订单状态错误');
        }

        if(!$model->save(['status' => 2,'finish_time' => time()])){
            $this->apiReturn(0,'操作失败，请稍后再试');
        }
        $this->apiReturn(1,'操作成功');
    }


    //服务评价
    public function eva(){
        $validate = new \think\validate([
            'order_id' => 'require',
            'kaopu' => 'require|between:0,5',
            'content' => 'max:100'
        ],[
            'order_id.require' => '订单id丢失',
            'kaopu.require' => '请选择靠谱指数',
            'kaopu.between' => '靠谱指数有误',
            'content.max' => '评价内容不得超过100个字符'
        ]);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(isset($this->post['image']) && trim($this->post['image']) != ''){
            if(count(explode(',',trim($this->post['image']))) > 6){
                $this->apiReturn(0,'最多可上传6张图片');
            }
        }

        $model = model('common/service_buy')->where('buy_user',UID)->where('id',intval($this->post['order_id']))->find();
        if(is_null($model)){
            $this->apiReturn(0,'订单不存在或已被删除');
        }
        if($model['status'] != 2){
            $this->apiReturn(0,'订单状态错误');
        }
       
        db()->startTrans();
        //修改订单状态
        if(!$model->save(['status' => 3])){
            db()->rollback();
            $this->apiReturn(0,'订单状态修改失败');
        }

        if(!db('service_eva')->insert([
            'issue_id' => $model['issue_id'],
            'kaopu' => intval($this->post['kaopu']),
            'add_time' => time()
        ])){
            db()->rollback();
            $this->apiReturn(0,'评价失败');
        }

        $avg_kaopu = db('service_eva')->where('issue_id',$model['issue_id'])->avg('kaopu');

        if(!model('common/user')->save(['kaopu' => $avg_kaopu],['id' => $model['issue_id']])){
            db()->rollback();
            $this->apiReturn(0,'操作失败，未知错误');
        }

        $this->post['foreign_key'] = $model['foreign_key'];
        $this->post['user_id'] = UID;
        $this->post['type'] = 3;
        //添加评论
        if(!model('common/comment')->allowField(true)->save($this->post)){
            db()->rollback();
            $this->apiReturn(0,'操作失败，未知错误');
        }
        db()->commit();
        $this->apiReturn(1,'评价成功');
    }

    /**
     * [dashang 服务打赏] 
     * @return [type] [description]
     */
    public function dashang(){
        $validate = new \think\validate([
            'order_id' => 'require',
            'pay_type' => 'require|in:0,1,2',
            'price' => 'require'
        ],[
            'order_id.require' => '参数order_id丢失',
            'pay_type.require' => '请选择支付方式',
            'pay_type.in' => '支付方式错误',
            'price.require' => '请输入支付金额'
        ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }
        if(floatval($this->post['price']) < 0.01){
            $this->apiReturn(0,'打赏金额不得小于1分');
        }
        $model = model('common/service_buy')->where('buy_user',UID)->where('id',intval($this->post['order_id']))->find();
        if(is_null($model)){
            $this->apiReturn(0,'订单不存在或已被删除');
        }

        $service_info = db('service')->where('id',$model['foreign_key'])->find();
        if(is_null($service_info) || $service_info['status'] == 0){
            $this->apiReturn(0,'该服务不存在或已被删除');
        }

        //余额支付
        if($this->post['pay_type'] == 0){

            if($this->user_info['balance'] < floatval($this->post['price'])){
                $this->apiReturn(0,'账户余额不足');
            }

            db()->startTrans();
            if(!db('user')->where('id',UID)->setDec('balance',floatval($this->post['price']))){
                db()->rollback();
                $this->apiReturn(0,'账户余额修改失败');
            }

            if(!db('user')->where('id',$model['issue_id'])->setInc('balance',floatval($this->post['price']))){
                db()->rollback();
                $this->apiReturn(0,'打赏失败，请稍后再试');
            }

            if(!db('bill')->insertAll([[
                    'user_id' => UID,
                    'type' => 9,
                    'num' => floatval($this->post['price']),
                    'foreign_key' => $model['id'],
                    'add_time' => time()
                ],[
                    'user_id' => $model['issue_id'],
                    'type' => 10,
                    'num' => floatval($this->post['price']),
                    'foreign_key' => $model['id'],
                    'add_time' => time()
                ]])){
                db()->rollback();
                $this->apiReturn(0,'交易明细添加失败');
            }

            if(!db('information')->insertAll([[
                    'user_id' => UID,
                    'type' => 9,
                    'content' => '服务-'.$service_info['title'].'打赏成功',
                    'add_time' => time()
                ],[
                    'user_id' => $model['issue_id'],
                    'type' => 10,
                    'content' => '服务-'.$service_info['title'].'被打赏'.floatval($this->post['price']).'元',
                    'add_time' => time()
                ]])){
                db()->rollback();
                $this->apiReturn(0,'消息通知添加失败');
            }

            if(!$model->save([
                'dashang' => 1,
                'ds_price' => floatval($this->post['price']),
                'ds_order_no' => date('YmdHis').rand(10000,99999),
                'ds_pay_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'订单状态修改失败');
            }
            db()->commit();
            $this->apiReturn(1,'打赏成功');
        }

        //微信
        if($this->post['pay_type'] == 1){
            $options = [
                'out_trade_no' => date('YmdHis').rand(10000,99999),
                'total_fee' => floatval($this->post['price']) * 100,
                'body' => '服务打赏',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                'attach' => serialize(['attach' => 5,'id' => intval($this->post['order_id'])])
            ];

            $pay = new Pay(config('pay'));

            try{
                $result = $pay->driver('wechat')->gateway('app')->apply($options);
                $this->apiReturn(1,'微信支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
        //支付宝支付
        if($this->post['pay_type'] == 2){
            $options = [
                'out_trade_no' => date('YmdHis').rand(10000,99999),
                'total_amount' =>  floatval($this->post['price']),
                'subject' => '服务打赏',
                'passback_params' => UrlEncode(serialize(['passback_params' => 5,'id' => intval($this->post['order_id'])]))
            ];
            $pay = new Pay(config('pay'));
            try{
                $result = $pay->driver('alipay')->gateway('app')->apply($options);
                $this->apiReturn(1,'支付宝支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
    }


    /**
     * [orderList 订单列表]
     * @return [type] [description]
     */
    public function orderList(){
        if(!isset($this->post['type']) || !in_array($this->post['type'],[0,1,2,3])){
            $this->apiReturn(0,'参数type丢失');
        }
        $where = [];
        if($this->post['type'] != 3){
            $where['b.status'] = $this->post['type'];
        }
        $list = db('service_buy')->alias('b')->join(['bz_service' => 's'],'s.id = b.foreign_key')->join(['bz_user' => 'u'],'u.id = s.user_id')
            ->where('buy_user',UID)->where($where)
            ->field('b.id as order_id,s.image,s.title,b.issue_id,b.service_type,order_no,b.status,photo_path,nick_name,dashang')
            ->order('b.add_time desc')
            ->limit(($this->p-1)*config('page_size'),config('page_size'))
            ->select();
        
        foreach($list as $key => $val){
            $list[$key]['image'] = empty($val['image']) ? '' : explode(',',$val['image'])[0];
        }

        $this->apiReturn(1,'订单列表',$list);
    }

    /**
     * [tousu 服务投诉]
     * @param  id     服务id
     * @return [type] [description]
     */
    public function tousu(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $model = model('common/service')->get(intval($this->post['id']));
        if(is_null($model) || $model['status'] != 1){
            $this->apiReturn(0,'该服务不存在或已被删除');
        }
       
        $res = db('service_tousu')->where('user_id',UID)->where('service_id',intval($this->post['id']))->find();
        if($res){
            $this->apiReturn(1,'投诉成功');
        }
        db()->startTrans();
        if(!db('service_tousu')->insert([
            'user_id' => UID,
            'service_id' => intval($this->post['id']),
            'add_time' => time()
        ])){
            db()->rollback();
            $this->apiReturn(0,'投诉失败，请稍后再试');
        }

        if(!$model->setInc('complain')){
            db()->rollback();
            $this->apiReturn(0,'投诉失败，请稍后再试');
        }
        db()->commit();
        $this->apiReturn(1,'投诉成功');
    }


    /**
     * [mySell 我的售卖]
     * @return [type] [被购买的服务列表]
     */
    public function mySell(){

    }
}
